package bpay

import (
	"context"
	"fmt"
	"strconv"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bpay/bpay"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Bpay{
		Url:        config.Url,
		SecretKey:  config.SecretKey,
		MerchantId: config.MerchantId,
		ReturnUrl:  config.ReturnUrl,
		NotifyUrl:  config.NotifyUrl,
		AppId:      config.AppId,
	}
}

type Bpay struct {
	SecretKey  string
	Url        string
	ReturnUrl  string
	NotifyUrl  string
	MerchantId string
	AppId      string
}
type Params struct {
	MerchantRef string `json:"merchant_ref"`
	Product     string `json:"product"`
	Amount      string `json:"amount"`
	Extra       extra  `json:"extra"`
}
type extra struct {
	FiatCurrency string `json:"fiat_currency"`
}
type Resp struct {
	OJid        int     `json:"ojid"`
	OrderId     string  `json:"orderid"`
	Title       string  `json:"title"`
	Amount      float64 `json:"amount"`
	ApiJumpUrl  string  `json:"api_jump_url"`
	Msg         string  `json:"msg"`
	Status      int     `json:"status"`
	Account     string  `json:"account"`
	Name        string  `json:"name"`
	CreateTime  string  `json:"createtime"`
	ExpiredTime string  `json:"expiredtime"`
}

// 代收订单创建
func (b *Bpay) Pay(ctx context.Context, req map[string]any) (resp base.PayResponse, err error) {
	mid := b.MerchantId
	orderID := req["orderNo"].(string)
	amount := fmt.Sprintf("%.2f", req["amount"])
	payType := b.AppId
	IP := headInfo.GetClientIp(ctx)
	version := "3"
	note := ""
	url := b.Url + "/pay/json"
	payResult, err := bpay.BPay(url, mid, orderID, amount, payType, IP, b.NotifyUrl, b.ReturnUrl, version, note, b.SecretKey)
	if err != nil {
		return resp, err
	}
	resp = base.PayResponse{
		Url:     payResult.ApiJumpUrl,
		Address: "",
		OrderNo: strconv.Itoa(payResult.OJid),
		Result:  strconv.Itoa(payResult.Status),
	}
	return resp, nil
}
